package se.teamscape.client.presenter;

import java.util.ArrayList;
import java.util.List;

import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.place.PlaceRequest;
import net.customware.gwt.presenter.client.place.TokenFormatter;
import se.teamscape.client.place.ListPlayersPlace;
import se.teamscape.client.rpc.CachingDispatchAsync;
import se.teamscape.client.rpc.DispatchCallback;
import se.teamscape.shared.model.Model;
import se.teamscape.shared.model.Team;
import se.teamscape.shared.rpc.DBQuery;
import se.teamscape.shared.rpc.ModelsQuery;
import se.teamscape.shared.rpc.ModelsQueryResult;

import com.google.inject.Inject;

/**
 * Presenter to list teams.
 * 
 * @author Andreas Borglin
 * 
 */
public class ListTeamsPresenter extends ListModelsPresenter {

    private final CachingDispatchAsync mDispatcher;
    private final TokenFormatter mFormatter;
    private boolean mHasData;

    @Inject
    public ListTeamsPresenter(Display display, EventBus eventBus, CachingDispatchAsync dispatcher, TokenFormatter formatter) {
        super(display, eventBus);
        this.mDispatcher = dispatcher;
        this.mFormatter = formatter;
    }

    @Override
    protected void onLazyBind() {

    }

    private void updateData() {

        DBQuery query = DBQuery.selectFrom(Team.class.getName());

        mDispatcher.executeWithCache(new ModelsQuery(query), new DispatchCallback<ModelsQueryResult>() {

            @Override
            public void callback(ModelsQueryResult result) {
                List<Model> models = result.getModels();
                List<String> places = new ArrayList<String>();
                for (Model model : models) {
                    // This is silly, but let's just show team players for
                    // now...
                    PlaceRequest req = new PlaceRequest(ListPlayersPlace.NAME).with(ListPlayersPlace.PARAM_TEAM_ID, model
                            .getId());
                    places.add(mFormatter.toHistoryToken(req));
                }

                display.setData(models, places);
                viewUpdated();
            }
        });

    }

    @Override
    protected void onRevealDisplay() {

        if (!mHasData) {
            updateData();
            mHasData = true;
        }

    }

}
